//
//  FirstPageViewController.swift
//  DriverSchoolAPP
//
//  Created by Logel on 2017/4/19.
//  Copyright © 2017年 Logel. All rights reserved.
//

import UIKit
import Alamofire
var APP_lat = ""
var APP_lon = ""
class FirstPageViewController: UIViewController,LgCallBack,AMapLocationManagerDelegate,AMapGeoFenceManagerDelegate{
    
    var pageView: CarouselView?
    var imgs:[UIImage] = []
    var ids = [String]()
    var pList = [FirsePage]()
    var locationManager:AMapLocationManager! = nil
    var type = 0
    var clickNum = 0
       override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManager = AMapLocationManager()
        locationManager.delegate = self
        locationManager.distanceFilter = 200
        //iOS 9（不包含iOS 9） 之前设置允许后台定位参数，保持不会被系统挂起
        locationManager.pausesLocationUpdatesAutomatically = false
        
        //iOS 9（包含iOS 9）之后新特性：将允许出现这种场景，同一app中多个locationmanager：一些只能在前台定位，另一些可在后台定位，并可随时禁止其后台定位。
        if UIDevice.current.systemVersion._bridgeToObjectiveC().doubleValue >= 9.0 {
            locationManager.pausesLocationUpdatesAutomatically = true
        }
        locationManager.locatingWithReGeocode = true
        //开始持续定位
        
        if (CLLocationManager.authorizationStatus() == .denied){
            print("未开启定位")
        }else{
            //允许使用定位服务的话，开启定位服务更新
            locationManager.startUpdatingLocation()
            print("定位开始")
            
        }
       
        
        getData()
        
        
        

    }
    
    
    func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!, reGeocode: AMapLocationReGeocode?) {
        APP_lat = "\(location.coordinate.latitude)"
        APP_lon = "\(location.coordinate.longitude)"
        print("location:{lat:\(location.coordinate.latitude); lon:\(location.coordinate.longitude); accuracy:\(location.horizontalAccuracy);};");
        
        if let reGeocode = reGeocode {
            print("reGeocode:%@", reGeocode)
        }
    }
    
  
    func getData(){
        asyn_req_post(method: M_FirstPage, cb: self, p: ["":"" as AnyObject])
    }
    
    // 设置轮播视图
    fileprivate func setupCarouselView() {
       let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 120)
        pageView = CarouselView(frame: frame)
        
        pageView?.images = imgs
        pageView?.scrollTime = 1.5
        
        self.view.addSubview(pageView!)
        
        // 点击事件
        pageView?.imageTapHandler = { (image, index) in
            print("111111")
            self.type = 9
            self.clickNum = index
            self.performSegue(withIdentifier: "toWeb", sender: nil)
            
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    

    @IBAction func toNearBy(_ sender: Any) {
        switch user.accountId {
        case "":
            self.performSegue(withIdentifier: "toLogin", sender: nil)
        default:
            if (CLLocationManager.authorizationStatus() == .denied){
                showMsg(msg: "请在设置中开启定位服务，以便我们能给你推荐驾校。")
            }else{
                self.performSegue(withIdentifier: "toNearBy", sender: nil)
            }
        }
       
    }
    

    
    func callBack(method: String, data: AnyObject) {
        let json = JSON(data)
        print(json)
        pList = parseFirstPageList(all: json["MobileBody"].arrayValue)
        for p in pList {
            
            if p.picture != "" {
                let img = getImageWithUrl(url: p.picture)
                imgs.append(img)
                ids.append(p.id)
            }

           
        }
        
        setupCarouselView()
        
        //let dt =  Data(contentsOf: URL(fileURLWithPath: "http://114.55.103.113/images/editor/1494724980502_3.jpg"))

    }

    @IBAction func toGoWeb(_ sender: UIButton) {
        type = sender.tag
        self.performSegue(withIdentifier: "toWeb", sender: nil)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        switch segue.identifier! {
        case "toWeb":
            let dest = segue.destination as! WebViewController
            switch type {
            case 1:
                dest.destUrl = F_TZ_URL
                dest.destTitle = "通知"
            case 2:
                dest.destUrl = F_FG_URL
                dest.destTitle = "法规"
            case 3:
                dest.destUrl = F_BZ_URL
                dest.destTitle = "标志"
            case 4:
                dest.destUrl = F_LC_URL
                dest.destTitle = "流程"
            case 9 :
                dest.destUrl = WEB_URL+"banner?id=\(ids[clickNum])"
                print()
            default:
                break
            }
        default:
            break
        }
    }
}
